/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccastestore.utils;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import it.unitn.science.matr155863_148346_145963.bccastestore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.Image;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.Product;
import java.io.File;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.sound.midi.SysexMessage;

/**
 *
 * @author berto
 */
public class ProductDetailsValidator {
    
          
    
    private static Date dateFutureFromString(String string) {
        try {
            SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy",Locale.ITALIAN);
            sf.setLenient(false);
            Date date=sf.parse(string);
            Calendar today = Calendar.getInstance();
            today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
            Date todayDate = today.getTime();
            if(date.compareTo(todayDate)==0){
                return null;
            }
            return date;
        } catch (Exception e) {
            return null;
        }
    }
    
    public static Product createProductMultypart(HttpServletRequest request,DBManager db,String dirName)
            throws Exception{
        MultipartRequest multi = new MultipartRequest(request, dirName, 10*1024*1024,
        "ISO-8859-1", new DefaultFileRenamePolicy());
        /*out.println("PARAMS:");
        Enumeration params = multi.getParameterNames();
        while (params.hasMoreElements()) {
            String name = (String)params.nextElement();
            String value = multi.getParameter(name);
            out.println(name + "=" + value);
        }
         */
        Product product=new Product();
        String name=multi.getParameter(Product.NAME);
        if(!isValidString(name)){
            throw new RuntimeException(""+Product.NAME);
        }else{
            product.setName(name);
        }
        try{
            int quantity=Integer.parseInt(multi.getParameter("quantity"));
            product.setQuantity(quantity);
        }catch(Exception ex){
            throw new RuntimeException("quantity");
        }
        //Setto l'immagine di default
        String imageStr=multi.getParameter(Product.IMAGE);
        try{
            if(!imageStr.equals(-1)){
                int imageId=Integer.parseInt(imageStr);
                Image image=db.getImage(imageId);
                if(image!=null){
                    product.setImageId(image.getId());
                    product.setImageName(image.getName());
                }else{
                    throw new RuntimeException(""+Product.IMAGE);
                }
            }
        }catch(Exception ex){
            throw new RuntimeException(""+Product.IMAGE);
        }
        String description=multi.getParameter(Product.DESCRIPTION);
        if(!isValidString(description)){
            throw new RuntimeException(""+Product.DESCRIPTION);
        }else{
            product.setDescription(description);
        }
        try{
            Integer category=Integer.parseInt(multi.getParameter(Product.CATEGORY));
            String categoryName=db.categoryExist(category);
            if(categoryName!=null){
                product.setCategoryId(category);
                product.setCategoryName(categoryName);
            }else{
                throw new RuntimeException(""+Product.CATEGORY);
            }
        }catch(Exception ex){
            throw new Exception(""+Product.CATEGORY);
        }
        try{
            Integer um=Integer.parseInt(multi.getParameter(Product.UM));
            String umName=db.umExist(um);
            if(umName!=null){
                product.setUmId(um);
                product.setUmName(umName);
            }else{
                throw new RuntimeException(""+Product.UM);
            }
        }catch(Exception ex){
            throw new Exception(""+Product.UM);
        }
        /*
        out.println();
        out.println("FILES:");
         * 
         */
        try{
            Enumeration files = multi.getFileNames();
            
            while (files.hasMoreElements()) {
                name = (String)files.nextElement();
                String filename = multi.getFilesystemName(name);
                /*
                String originalFilename = multi.getOriginalFileName(name);
                String type = multi.getContentType(name);
                File f = multi.getFile(name);
                out.println("name: " + name);
                out.println("filename: " + filename);
                out.println("originalFilename: " + originalFilename);
                out.println("type: " + type);
                if (f != null) {
                    out.println("f.toString(): " + f.toString());
                    out.println("f.getName(): " + f.getName());
                    out.println("f.exists(): " + f.exists());
                    out.println("f.length(): " + f.length());
                }
                */
                int imageId=db.addImage(filename);
                product.setImageId(imageId);
                product.setImageName(filename);
            }
        }catch(Exception ex){
            throw new Exception("image");
        }   
        return product;
    }
    
    public  static Product createProduct(HttpServletRequest request,DBManager db) throws Exception{
        Product product=new Product();
        String name=request.getParameter(Product.NAME);
        if(!isValidString(name)){
            throw new RuntimeException(""+Product.NAME);
        }else{
            product.setName(name);
        }
        
        try{
            Integer quantity=Integer.parseInt(request.getParameter(Product.QUANTITY));
            product.setQuantity(quantity);
        }catch(Exception ex){
            throw new Exception(""+Product.QUANTITY);
        }
        
        
        String imageSrc=request.getParameter("image_src");
        try{
            if(imageSrc!=null){
                product.setImageId(-1);
                product.setImageName("upload");
            }else{
                String imageStr=request.getParameter(Product.IMAGE);
                int imageId=Integer.parseInt(imageStr);
                Image image=db.getImage(imageId);
                if(image!=null){
                    product.setImageId(image.getId());
                    product.setImageName(image.getName());
                }else{
                    throw new Exception(""+Product.IMAGE);
                }
            }
        }catch(Exception ex){
            throw new RuntimeException(""+Product.IMAGE);
        }
        String description=request.getParameter(Product.DESCRIPTION);
        if(!isValidString(description)){
            throw new Exception(""+Product.DESCRIPTION);
        }else{
            product.setDescription(description);
        }
        try{
            Integer category=Integer.parseInt(request.getParameter(Product.CATEGORY));
            String categoryName=db.categoryExist(category);
            if(categoryName!=null){
                product.setCategoryId(category);
                product.setCategoryName(categoryName);
            }else{
                throw new Exception(""+Product.CATEGORY);
            }
        }catch(Exception ex){
            throw new Exception(""+Product.CATEGORY);
        }
        try{
            Integer um=Integer.parseInt(request.getParameter(Product.UM));
            String umName=db.umExist(um);
            if(umName!=null){
                product.setUmId(um);
                product.setUmName(umName);
            }else{
                throw new Exception(""+Product.UM);
            }
        }catch(Exception ex){
            throw new Exception(""+Product.UM);
        }
        return product;
    }
    
    private static boolean isValidString(String string){
        boolean valid=false;
        if(string!=null){
            int i=0;
            while((valid==false)&&(i<string.length())){
                if(string.charAt(i)==' '){
                    i++;
                }else{
                    valid=true;
                }
            }
        }
        return valid;
    }

    public static Product createValidateEditProduct(HttpServletRequest request, DBManager db) throws Exception {
        Product product;
        //Non c'e' il prodotto ritorno null
        try{
            Integer id=Integer.parseInt(request.getParameter("id"));
            product=db.getProduct(id);
        }catch(Exception ex){
            return null;
        }
        if(product==null){
            return null;
        }
        //Il prodotto c'e' provo a modificarlo e in caso dico i campi errati
        try{
            Integer quantity=Integer.parseInt(request.getParameter(Product.QUANTITY));
            product.setQuantity(quantity);
        }catch(Exception ex){
            throw new Exception(""+Product.QUANTITY);
        }
        String description=request.getParameter(Product.DESCRIPTION);
        if(!isValidString(description)){
            throw new Exception(""+Product.DESCRIPTION);
        }else{
            product.setDescription(description);
        }
        return product;
    }
    
}
